package com.czk.gulimall.search.thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 单个任务完成的组合
 *
 * @Author:ChenZhangKun
 * @Date: 2022/2/10 15:52
 */
public class CompletableFutureTest4 {
    private static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 第一个任务
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务一启动了");
            int i = 10 / 2;
            System.out.println("任务一结束了");
            return i;
        }, executor);
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务二启动了");
            int i = 10 / 2;
            System.out.println("任务二结束了");
            return i;
        }, executor);


        // 两任务有一个做完就执行任务3
        future1.runAfterEither(future2, () -> {
            System.out.println("执行任务3");
        });


        // 可以感知结果，不返回结果
        future1.acceptEither(future2, (f1) -> {
            System.out.println(f1);
        });

        // 感知结果，有返回值
        CompletableFuture<Integer> integerCompletableFuture = future1.applyToEither(future2, (f1) -> f1 * 2);
        System.out.println(integerCompletableFuture.get());
    }
}
